//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using System.Text;
using Content = CommunityServer.Components.Content;

namespace CommunityServer.Controls 
{
	/// <summary>
	/// simple content editor
	/// </summary>
	public class EditContent : TemplatedWebControl, IPostBackEventHandler
	{
		TextBox _name;
		TextBox _headline;
		ITextEditor _content;
		int _id = 0;
		bool _hidden = false, _showname = false;

		public EditContent() 
		{
		}

		#region overridden methods
		protected override void AttachChildControls()
		{
			_content = (ITextEditor)FindControl("content");
			_name = (TextBox)FindControl("name");
			_headline = (TextBox)FindControl("headline");

			// the hidden flag here signifies that the content will be flagged as
			// hidden and hence not listed or searched. we're using the showname
			// parameter to specify this temporarily, but will eventually have
			// a different parameter..
			_hidden = !_showname;

			if (!_hidden)
            {
                Control nr = FindControl("NameRow");
                if(nr != null)
                    nr.Visible = true;

                Control hr = FindControl("HeadlineRow");
                if(hr != null)
                    hr.Visible = true;
            }
		}

		protected override void OnLoad(EventArgs e)
		{
			CSContext cntx = CSContext.Current;
			if(!cntx.User.IsAdministrator)
                throw new CSException(CSExceptionType.AccessDenied,"You do not have permission to edit this item");

			base.OnLoad (e);

			EnsureChildControls();

			Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);

			if (!Page.IsPostBack)
			{
				CommunityServer.Components.Content content = null;
				if (_id != 0)
					content = Contents.GetContent(_id,false);   // making it strongly typed to keep from conflicting with Content class in asp.net 2.0

				if (content != null)
				{
					_content.Text = content.Body;
					_name.Text = content.Name;
					_headline.Text = content.Title;
				}
				else if (!Globals.IsNullorEmpty(Page.Request.QueryString["clientid"]))
				{
					StringBuilder script = new StringBuilder();
					script.AppendFormat("<input type=\"hidden\" name=\"{0}_ParentContent\" id=\"{0}_ParentContent\" />", this.ClientID);
					script.Append("<script language=\"javascript\" type=\"text/javascript\">");
					script.Append("try { if (window.parent && window.parent.Telligent_Modal) { ");
					script.AppendFormat("var pContent = window.parent.document.getElementById('{0}').childNodes[0].childNodes[0]; ", JavaScript.Encode(Page.Request.QueryString["clientID"]));
					script.Append("if (pContent && pContent.innerHTML) { ");
					script.AppendFormat("document.getElementById('{0}_ParentContent').value = pContent.innerHTML;", this.ClientID);
					script.Append(Page.GetPostBackClientEvent(this, "reloadContent"));
					script.Append("	} } } catch (e) {} </script>");

					Page.RegisterStartupScript(this.ClientID + "_ReloadContent", script.ToString());
				}
			}

			string titlename = _name.Text;
			if (titlename.Length == 0)
				titlename = ResourceManager.GetString("Content") ;
			Head.AddTitle(string.Concat(ResourceManager.GetString("Editing"), " ", titlename), Context);

			// find the validators
			string error = ResourceManager.GetString("Content_Validator");
			RequiredFieldValidator v1 = (RequiredFieldValidator) FindControl("NameValidator");
			RequiredFieldValidator v2 = (RequiredFieldValidator) FindControl("HeadlineValidator");
			v1.ErrorMessage = v2.ErrorMessage = error;

			// find the buttons
			IButton button = FindButton("SaveButton");
			button.Text = ResourceManager.GetString("Content_Save");
			button.Click += new EventHandler(SaveContent_Click);
			
			button = FindButton("DeleteButton");
			if (button != null)
			{
				if (_id == 0)
				{
					button.Visible = false;
				}
				else
				{
					button.Text = ResourceManager.GetString("Content_Delete");
					button.Click += new EventHandler(DeleteContent_Click);
				}
			}
		}
		#endregion

		#region Event Handlers
		void SaveContent_Click (Object sender, EventArgs e) 
		{
			// create/update content
			string name = Contents.StripBadChars(_name.Text); // making strongly type for Content class name conflict in asp.net 2.0
			if (name.Length == 0)
				name = CSContext.Current.QueryString["contentname"];

			// making it fully qualified to resolve naming conflict with Content class in asp.net
			CommunityServer.Components.Content content = new CommunityServer.Components.Content(_id, name, _headline.Text, _content.Text, _content.Text, DateTime.Now, _hidden);
			
            if(content.ID > 0)
                Contents.Update(content);
            else
                Contents.Add(content);
            

			string path = Contents.ArticleUrl(name);

			if (UsedByModal())
				Modal.ClosePage(this.Page, "'" + path + "'");
			else
				Page.Response.Redirect(path, true);
		}

		void DeleteContent_Click (Object sender, EventArgs e) 
		{
			// making it fully qualified to resolve naming conflict with Content class in asp.net
			CommunityServer.Components.Content content = Contents.GetContent(_id,true);
            Contents.Delete(content);

			string path = "~/";
			path = Context.Response.ApplyAppPathModifier(path);

			if (UsedByModal())
				Modal.ClosePage(this.Page, "'" + path + "'");
			else
				Page.Response.Redirect(path, true);
		}
		#endregion

		#region Properties
		/// <summary>
		///  the content to display from database, by id
		/// </summary>
		public int ContentID
		{
			set {_id = value;}
		}

		/// <summary>
		/// take content ID/name from querystring if true
		/// </summary>
		public bool FromQueryString
		{
			set 
			{
				if (value == true)
					ContentID = Globals.SafeInt(CSContext.Current.QueryString["contentid"], 0);
			}
		}

		public bool ShowName
		{
			get {return _showname;}
			set {_showname = value;}
		}
		
		/// <summary>
		/// whether the control is modal or own page - affects how it closes
		/// </summary>
		public bool UsedByModal()
		{
			MPContainer container = (MPContainer)Page.FindControl("MPContainer");
			return container.IsModal;
		}
		#endregion

		#region IPostBackEventHandler Members

		public void RaisePostBackEvent(string eventArgument)
		{
			if (eventArgument == "reloadContent")
			{
				EnsureChildControls();

				this._content.Text = Page.Request.Form[this.ClientID + "_ParentContent"];
			}
		}

		#endregion
	}
}